//
//  WYCSetDissController.m
//  51信用卡
//
//  Created by 中企互联 on 2017/11/2.
//  Copyright © 2017年 中企互联. All rights reserved.
//

#import "WYCSetDissController.h"
//#import "WYCOpinionController.h"
//#import "WYCSetPassController.h"
#import "WQCSetPasswordViewController.h"
#import "WYCLoginViewController.h"
#import "SetGestureLockViewController.h"
#import "WYCAboutMeController.h"
#import "configuration.h"
#import "WQCFeedViewController.h"
#import "AppDelegate.h"
//#import "WYCZhifusetController.h"
@interface WYCSetDissController ()<UITableViewDelegate,UITableViewDataSource,UIApplicationDelegate>{
    
    BOOL first;
    CGFloat sizeM;
}


@property(nonatomic,strong)UITableView * tableView;

/** 手势按钮*/
@property(nonatomic,strong)UIButton * touchpassbutton;

@property(retain,nonatomic) UISwitch * mySwitch;

/** 手势按钮*/
@property(nonatomic,strong)UIButton * folderbutton;
@property(nonatomic,strong)NSArray  *dataSource;
@property(nonatomic,strong)NSArray  *titleSource;


@end

@implementation WYCSetDissController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = WYCGlobalBg;
    
    
    //setNav
    [self setNav];
    
    
    //创建表视图
    [self setupTableView];
    
    
    
}

#pragma make -------->>TableView
- (void)setupTableView{
    CGRect frame=CGRectMake(0, 0, 0,0);
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,kDevice_Is_iPhoneX ?52:28, ScreenWidth,  ScreenHeight) style:UITableViewStyleGrouped];
    if (ScreenHeight == 812) {
        _tableView.frame = CGRectMake(0, 20, ScreenWidth, ScreenHeight);
        _tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0);
        _tableView.scrollIndicatorInsets = _tableView.contentInset;
    }
    self.tableView.dataSource = self;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.tableView.delegate = self;
    self.tableView.tableHeaderView=[[UIView alloc]initWithFrame:frame];
    self.tableView.sectionFooterHeight = 5;
    self.tableView.sectionHeaderHeight = 5;
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;//分割线
    
    [self.view addSubview:self.tableView];
    
    _dataSource=@[@"手势密码",@"密码设置",@"关于我们"];
    _titleSource = @[@"清除缓存",@"意见反馈"];
}
#pragma make ------->>setNav
- (void)setNav {
    self.navigationItem.title = @"设置";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self.navigationController.navigationBar setBarTintColor:wycMain];
    
    self.view.backgroundColor = WYCGlobalBg;
}

#pragma make ------->>退出登录点击事件
- (void)cellButtonClick{
   
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:[UIColor whiteColor]]; //字体颜色
    [SVProgressHUD setBackgroundColor:[UIColor blackColor]];   //背景颜色
    [HttpTool POST:Userlogout params:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        if ([[responseObject objectForKey:@"code"] intValue] == 0)
        {
            [WYCAccountTool clearAccount];
            WYCLoginViewController * login = [[WYCLoginViewController alloc] init];
            AppDelegate *myDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
            myDelegate.window.rootViewController = login;
            
        }else{
            [SVProgressHUD showImage:[UIImage imageNamed:@""] status:msgStr];
            
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:Failed];
    }];
}

#pragma mark tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //分组数 也就是section数
    return 3;
}

//设置每个分组下tableview的行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return _dataSource.count;
    }
    else if (section==1) {
        return _titleSource.count;
    }
    else{
        return 1;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

//设置每行对应的cell（展示的内容）
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifer=@"cell";
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identifer];
    if (cell==nil) {
        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifer];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    if (indexPath.section==0) {
        cell.textLabel.text=[_dataSource objectAtIndex:indexPath.row];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        
        if (indexPath.row ==0) {
            _mySwitch = [[UISwitch alloc]init];
            _mySwitch.frame=CGRectMake(ScreenWidth - 200 * px, 10, 80 * px, 40);
            
            NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
            if ([useDef objectForKey:@"first"]) {
                
                [_mySwitch setOn:YES animated:NO];
            } else {
                [_mySwitch setOn:NO animated:NO];
            }
            
            [_mySwitch addTarget:self action:@selector(swChange:) forControlEvents:UIControlEventValueChanged];
            [cell addSubview:_mySwitch];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
        }
        else
        {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            
        }
    }else if(indexPath.section==1) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        cell.textLabel.text=[_titleSource objectAtIndex:indexPath.row];
        if (indexPath.row == 0) {
            self.folderbutton = [[UIButton alloc] init];
            self.folderbutton.titleLabel.font = [UIFont systemFontOfSize:SmallFont];
            [self.folderbutton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            self.folderbutton.frame = CGRectMake(ScreenWidth - 300 * px, 10, 220 * px, 30);
            NSString *str = [NSString stringWithFormat:@"%.2fM",sizeM];
            
            [self.folderbutton addTarget:self action:@selector(folderButtonClick) forControlEvents:UIControlEventTouchUpInside];
            [self.folderbutton setTitle:str forState:UIControlStateNormal];
            [cell.contentView addSubview:self.folderbutton];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            
        }
    }
    else
    {
        cell.textLabel.text=@"退出登陆";
        cell.textLabel.textColor = wycMain;
        
        cell.textLabel.textAlignment=NSTextAlignmentCenter;
    }
    return cell;
}
//参数传入开关对象本身
- (void) swChange:(UISwitch*) sw{
    
    if(sw.on == YES){
        first = YES;
        
        NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
        
        // 保存用户数据
        
        [useDef setBool:first forKey:@"first"];
        
        [useDef synchronize];
        SetGestureLockViewController * mewallet = [[SetGestureLockViewController alloc] init];
        mewallet.myflag =@"456";
        mewallet.string = YES;
        [self.navigationController pushViewController:mewallet animated:NO];
    }else{
        //关闭手势
        NSUserDefaults *useDef = [NSUserDefaults standardUserDefaults];
        
        // 保存用户数据
        [useDef removeObjectForKey:@"first"];
        
        [useDef synchronize];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section ==0) {
        
       
        if (indexPath.row == 1) {
            WQCSetPasswordViewController * SetPass = [[WQCSetPasswordViewController alloc] init];
            [self.navigationController pushViewController:SetPass animated:NO];
        }
        
        if (indexPath.row == 2) {
            WYCAboutMeController * opininon = [[WYCAboutMeController alloc] init];
            [self.navigationController pushViewController:opininon animated:NO];
        }
        
        
    }
    else if (indexPath.section == 1)
    {
        
        if (indexPath.row == 1) {
            WQCFeedViewController  *feedView = [[WQCFeedViewController alloc]init];
            [self.navigationController pushViewController:feedView animated:YES];
        }
    }
    else
    {
        [self cellButtonClick];
    }
    
    
}

// 缓存大小
- (CGFloat)folderSize{
    CGFloat folderSize = 0.0;
    
    //获取路径
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)firstObject];
    
    //获取所有文件的数组
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",files.count);
    
    for(NSString *path in files) {
        
        NSString*filePath = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",path]];
        
        //累加
        folderSize += [[NSFileManager defaultManager]attributesOfItemAtPath:filePath error:nil].fileSize;
    }
    //转换为M为单位
    sizeM = folderSize /1024.0/1024.0;
    
    
    
    return sizeM;
}
- (void)folderButtonClick{
    
    //===============清除缓存==============
    //获取路径
    NSString*cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];
    
    //返回路径中的文件数组
    NSArray*files = [[NSFileManager defaultManager]subpathsAtPath:cachePath];
    
    NSLog(@"文件数：%ld",[files count]);
    for(NSString *p in files){
        NSError*error;
        
        NSString*path = [cachePath stringByAppendingString:[NSString stringWithFormat:@"/%@",p]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:path])
        {
            BOOL isRemove = [[NSFileManager defaultManager]removeItemAtPath:path error:&error];
            if(isRemove) {
                NSLog(@"清除成功");
                [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"缓存已清空"];
                [self.folderbutton setTitle:@"0.00M" forState:UIControlStateNormal];
                
            }else{
                
                NSLog(@"清除失败");
                
            }
        }
    }
    
}
@end

